/**
 * @author yxw
 * date : 2013年11月3日 下午10:29:25 
 */
package com.tzinfo.tzt.activity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.util.MyApplication;
import com.tzinfo.tzt.activity.view.ImagePagerAdapter;
import com.tzinfo.tzt.activity.view.MyProgressDialog;
import com.tzinfo.tzt.activity.view.VerticalScrollView;
import com.tzinfo.tzt.config.AppDataConfig;
import com.tzinfo.tzt.domain.MyResultList;
import com.tzinfo.tzt.domain.OldhouseVillage;
import com.tzinfo.tzt.util.HttpTools;
import com.tzinfo.tzt.util.JsonTools;

public class OldhouseVillageAcitivity extends BaseActivity implements
		OnClickListener {

	// 传递数据
	private int villageId;
	// 标志
	private boolean collectionChecked = false;

	// 工具类
	private List<Map<String, Object>> imgData;
	private Dialog dialog;
	private MyResultList jsonResult;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private Intent thisIntent;
	private OldhouseVillage detail;
	private DisplayImageOptions options;

	// UI组件
	private Button backBtn, collectionBtn;
	private VerticalScrollView mScrollView;
	private ImageView mapView, noPicView, pricePicView, priceIncreaseView;
	private TextView[] textViews = new TextView[15];
	private ViewPager imagesPager;
	private ImagePagerAdapter imagePagerAdapter;
	private RelativeLayout oldHouseLayout;
	private RelativeLayout mapLayout;

	private Drawable drawableSelected;
	private Drawable drawableNormal;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_oldvillage_detail);
		thisIntent = this.getIntent();
		villageId = thisIntent.getIntExtra("villageId", 0);
		init();

	}

	private void init() {

		// 加载图片
		drawableSelected = getResources().getDrawable(
				R.drawable.top_50collection_selected);
		drawableNormal = getResources().getDrawable(
				R.drawable.top_50collection_normal);
		drawableSelected.setBounds(0, 0, drawableSelected.getMinimumWidth(),
				drawableSelected.getMinimumHeight());
		drawableNormal.setBounds(0, 0, drawableNormal.getMinimumWidth(),
				drawableNormal.getMinimumHeight());

		mapLayout =(RelativeLayout)this.findViewById(R.id.layout_house_location);
		mapLayout.setOnClickListener(this);
		
		noPicView = (ImageView) this.findViewById(R.id.img_no_Village_images);
		backBtn = (Button) this.findViewById(R.id.bt_back);
		backBtn.setOnClickListener(this);
		collectionBtn = (Button) this.findViewById(R.id.bt_collection);
		collectionBtn.setOnClickListener(this);

		// layout
		oldHouseLayout = (RelativeLayout) this
				.findViewById(R.id.layout_same_community_second);
		oldHouseLayout.setOnClickListener(this);

		// Infos
		textViews[0] = (TextView) this.findViewById(R.id.text_Village_Name);
		textViews[1] = (TextView) this
				.findViewById(R.id.text_Village_AveragePrice);
		textViews[2] = (TextView) this
				.findViewById(R.id.text_Village_PriceIncrease);
		priceIncreaseView = (ImageView) this
				.findViewById(R.id.img_PriceIncrease_up_or_down);
		textViews[3] = (TextView) this
				.findViewById(R.id.text_Village_HouseCount);
		textViews[4] = (TextView) this.findViewById(R.id.text_Village_Address);
		textViews[5] = (TextView) this
				.findViewById(R.id.text_Village_BuildType);
		textViews[6] = (TextView) this
				.findViewById(R.id.text_Village_BuildYear);
		textViews[7] = (TextView) this
				.findViewById(R.id.text_Village_Developer);

		textViews[8] = (TextView) this
				.findViewById(R.id.text_Village_ManageCompany);
		textViews[9] = (TextView) this
				.findViewById(R.id.text_Village_PriceInfo);
		// 价格行情曲线图地址
		pricePicView = (ImageView) this.findViewById(R.id.img_Village_PricePic);
		textViews[10] = (TextView) this
				.findViewById(R.id.text_Village_Address2);
		// 显示地图控件
		mapView = (ImageView) this.findViewById(R.id.img_Village_Address);
		textViews[11] = (TextView) this.findViewById(R.id.text_Village_Transit);
		textViews[12] = (TextView) this.findViewById(R.id.text_Village_School);
		textViews[13] = (TextView) this
				.findViewById(R.id.text_Village_Describe);
		textViews[14] = (TextView) this
				.findViewById(R.id.text_Village_LifeSupport);

		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.ic_empty)
				.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
				.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
		imagesPager = (ViewPager) this.findViewById(R.id.pager_Village_images);
		dialog = new MyProgressDialog(this).createDialog(getResources()
				.getString(R.string.loading));
		// 加载进度条
		dialog.show();
		mScrollView = (VerticalScrollView) this.findViewById(R.id.scrollview);
		mScrollView.smoothScrollTo(0, 0);
		new Thread(getOldhouseVillageDetailRun).start();
	}

	private void getDataError(String ERRORMESSAGE) {
		new AlertDialog.Builder(this).setCancelable(false)
				.setMessage(ERRORMESSAGE)
				.setPositiveButton(getResources().getString

				(R.string.cancel), new DialogInterface.OnClickListener()

				{
					public void onClick

					(DialogInterface dialog, int which) {
						finish();
					}
				}).setNegativeButton(getResources().getString

				(R.string.try_again), new DialogInterface.OnClickListener()

				{
					public void onClick(

					DialogInterface dialogInterface, int

					whichButton) {
						dialog.show();
						new Thread(getOldhouseVillageDetailRun).start();
					}
				}).show();
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case 1:
				updateUI();
				dialog.dismiss();
				break;
			case -1:
				getDataError((String) msg.obj);
				break;
			case 5:
				break;
			case 7:
				break;
			case 0:
				break;
			}
		}
	};

	/**
	 * 线程 得到新房列表
	 */
	Runnable getOldhouseVillageDetailRun = new Runnable() {

		@Override
		public void run() {
			Message msg = handler.obtainMessage();
			String jsonString;
			String url = AppDataConfig.oldUrl + AppDataConfig.OldhouseVillage
					+ "?id=" + villageId;
			Log.e("url", url);
			jsonString = HttpTools.getJsonContent(url);
			Log.e("JsonString", jsonString);
			jsonResult = JsonTools.getOldhouseVillage(jsonString);
			getData();
			if (jsonResult.getSuccess()) {
				msg.arg1 = 1;
			} else {
				msg.arg1 = -1;
				msg.obj = jsonResult.getErrorMessage();
			}
			handler.sendMessage(msg);
		}
	};

	// 得到data数据
	private void getData() {
		imgData = new ArrayList<Map<String, Object>>();
		Map<String, Object> map;
		if (jsonResult.getSuccess()) {
			Log.e("size", jsonResult.getData().size() + "");
			detail = (OldhouseVillage) jsonResult.getData().get(0);
			List<String> pics = detail.getPics();
			if (pics == null || pics.size() == 0) {
				map = new HashMap<String, Object>();
				map.put("img", R.drawable.ic_empty);
				imgData.add(map);
			}
			for (int i = 0; i < pics.size(); i++) {
				map = new HashMap<String, Object>();
				map.put("img", pics.get(i));
				imgData.add(map);
			}

		}
	}

	private void updateUI() {
		if (detail.getPics().size() == 0) {
			imagesPager.setVisibility(View.GONE);
			noPicView.setVisibility(View.VISIBLE);
		}
		imagePagerAdapter = new ImagePagerAdapter(this, imgData,
				R.layout.item_pager_image, new String[] { "img" },
				new int[] { R.id.image });
		imagesPager.setAdapter(imagePagerAdapter);
		imagesPager.setCurrentItem(0);

		// getInfos
		textViews[0].setText(detail.getName());

		double averagePrice = Double.parseDouble(detail.getAveragePrice());
		DecimalFormat df = new DecimalFormat("#.00");
		textViews[1].setText(df.format(averagePrice) + "元/平");
		double priceIncrease = detail.getPriceIncrease();
		if (priceIncrease < 0) {
			priceIncreaseView.setImageResource(R.drawable.price_down);
		}
		textViews[2].setText(priceIncrease + "%");
		textViews[3].setText(detail.getHouseCount()+"套");
		textViews[4].setText(detail.getAddress());
		textViews[5].setText(detail.getBuildType());
		textViews[6].setText(detail.getBuildYear());
		textViews[7].setText(detail.getDeveloper());

		// 显示百度地图
		String mapUrl = "http://api.map.baidu.com/staticimage?center="
				+ detail.getLon() + "," + detail.getLat() + "&width="
				+ MyApplication.widthPixels + "&height="
				+ MyApplication.widthPixels * 0.75 + "&zoom=12";
		imageLoader.displayImage(mapUrl, mapView, options);
		textViews[8].setText(detail.getManageCompany());
		textViews[9].setText(detail.getPriceInfo());
		textViews[10].setText(detail.getAddress());
		textViews[11].setText(detail.getTransit());
		textViews[12].setText(detail.getSchool());
		String describe = detail.getDescribe();
		if (describe == null || "".equals(describe.trim())) {
			describe = "该小区目前没有描述！";
		}
		textViews[13].setText(describe);

		String lifeSupport = detail.getLifeSupport();
		if (lifeSupport == null || "".equals(lifeSupport.trim())) {
			lifeSupport = "该小区目前没有生活配套的信息！";
		}
		textViews[14].setText(lifeSupport);
		imageLoader.displayImage(detail.getPricePic(), pricePicView, options);

		// 检测是否已收藏
		if ((collectionChecked = collectionService.getCommunityById(detail.getID()+"") != null ? true
				: false)) {
			collectionBtn.setCompoundDrawables(drawableSelected, null, null,
					null);
		}

		mScrollView.smoothScrollTo(0, 0);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_back:
			this.finish();
			break;
		case R.id.bt_collection:
			// 收藏与取消
			if (collectionChecked) {
				// sharedPreferences.removeMapItemMessage(
				// AppDataConfig.CollectionKeys[1], newhouseList.getId() + "");
				collectionService.deleteCommunityById(detail.getID() + "");
				collectionBtn.setCompoundDrawables(drawableNormal, null, null,
						null);
				collectionChecked = false;
				Toast.makeText(this, "取消收藏！", 5000).show();
			} else {
				// sharedPreferences.saveMapItemMessage(
				// AppDataConfig.CollectionKeys[1], newhouseList.getId() + "",
				// newhouseList);
				collectionService.saveCommunity(detail);
				collectionBtn.setCompoundDrawables(drawableSelected, null,
						null, null);
				Toast.makeText(this, "收藏成功！", 5000).show();
				collectionChecked = true;
			}
			break;

		case R.id.layout_same_community_second:
			Intent samecommunityIntent = new Intent(this,
					OldSameCommunityListActivity.class);
			samecommunityIntent.putExtra("villageId", detail.getID());
			samecommunityIntent.putExtra("villageName", detail.getName());
			startActivity(samecommunityIntent);
			break;
		case R.id.layout_house_location:
			Intent mapIntent=new Intent(this, MapRoutePlanActivity.class);
			mapIntent.putExtra("lon", detail.getLon());
			mapIntent.putExtra("lat", detail.getLat());
			mapIntent.putExtra("houseName", detail.getName());
			startActivity(mapIntent);
			break;
		}

	}
}
